package lsf.aHttp

import Strs
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.koushikdutta.async.http.AsyncHttpClient
import com.koushikdutta.async.http.AsyncHttpGet
import com.koushikdutta.async.http.AsyncHttpPost
import com.koushikdutta.async.http.AsyncHttpResponse
import com.koushikdutta.async.http.body.MultipartFormDataBody
import com.koushikdutta.async.http.body.StringBody
import kotlinx.android.synthetic.main.client.*
import java.io.File


var root = ""
    private set

class ClientActivity : Activity() {

    private val client = AsyncHttpClient.getDefaultInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.client)
        sf.setText(sd)
    }

    private fun toast(s: String?) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show()
    }

    fun copy(v: View?) {
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        cm.primaryClip = ClipData.newPlainText("Label", tv?.text)
        tv.text = ""
    }

    fun recvText(v: View?) {
        client.executeString(AsyncHttpGet(Strs.adjust(et.text.toString())), object : AsyncHttpClient.StringCallback() {
            override fun onCompleted(e: Exception?, response: AsyncHttpResponse?, result: String?) = runOnUiThread {
                if (e != null) toast(e.localizedMessage)
                else tv?.text = result
            }
        })
    }

    fun recvFile(v: View?) {
        root = "http://" + et.text + ":8888/d"
        startActivity(Intent(this, FileActivity::class.java))
    }

    fun sendText(v: View?) {
        val post = AsyncHttpPost("http://" + et.text + ":8888/s")
        post.body = StringBody(send.text.toString())
        client.execute(post) { e, response -> }
    }

    fun sendFile(v: View?) {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, 1)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode != RESULT_OK) return

        val path = data!!.data.path
        toast(path)

        val post = AsyncHttpPost("http://" + et.text + ":8888/s")
        val body = MultipartFormDataBody()
        body.addFilePart("file", File(sf.text.toString()))
        post.body = body
        client.execute(post) { e, response -> }
    }

    fun toWeb(v: View?) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://" + et.text + ":8888/")))
    }
}

